#include <iostream>
#include <string>
#include <errno.h>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

void ChildWrite(int wfd)
{
    string message = "father, i am your son process.";
    int cnt = 0;
    while(true)
    {
        cnt++;
        string wmessage = message;
        wmessage += "cnt = ";
        wmessage += to_string(cnt);
        write(wfd, wmessage.c_str(), wmessage.size());
        printf("Child send: %s\n", wmessage.c_str());
        sleep(1);
    }
}

void FatherRead(int rfd)
{
    char buff[1024];
    while(true)
    {
        ssize_t n = read(rfd,buff,sizeof(buff)-1);
        buff[n]=0;
        printf("Father get: %s\n", buff);
        // cout << buff << endl;
    }
}

int main()
{
    int pipefd[2];
    int n = pipe(pipefd);   //打开管道
    if (n != 0)
    {
        cerr << "errno" << errno << ":" << "errstring : " << strerror(errno) << std::endl;
        return 1;
    }
    //打印管道文件的r和w文件的文件描述符
    std::cout << "pipefd[0]: " << pipefd[0] << ", pipefd[1]: " << pipefd[1] << std::endl;

    //我们让子进程写，父进程读
    int pid = fork();
    if(pid == 0) //子进程
    {
        close(pipefd[0]);
        ChildWrite(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }

    //父进程
    close(pipefd[1]);
    FatherRead(pipefd[0]);

    close(pipefd[0]);
    int status = 0;
    waitpid(pid, &status, 0);
    return 0;
}